import IconApp from '@/components/icon/IconApp';
import IconBiliBili from '@/components/icon/IconBiliBili';
import IconDouyin from '@/components/icon/IconDouyin';
import IconKuaishou from '@/components/icon/IconKuaishou';
import IconToutiao from '@/components/icon/IconToutiao';
import IconWeb from '@/components/icon/IconWeb';
import IconWeChatChannels from '@/components/icon/IconWeChatChannels';
import IconWeChatOfficialAccount from '@/components/icon/IconWeChatOfficialAccount';
import IconWeibo from '@/components/icon/IconWeibo';
import { forwardRecordToMonth, pageRecord, saveVerify } from '@/services/api/api-assess-week-emphasize-record';
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Alert, DatePicker, Flex, message, Select, Space, Tag } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import TableExhibition from '../exhibition/TableExhibition';
import AddRecord from './AddRecord';
import DetailRecord from './DetailRecord';
dayjs.extend(customParseFormat);
const dateFormat = 'YYYY-MM-DD';
const weekStart = 1; // 1表示周一是一周的开始，0表示周日是一周的开始

interface TabRecordProps {}

const TabRecord: React.FC<TabRecordProps> = ({}) => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();

  const [searchParam, setSearchParamState] = useState({
    dataName: '',
    dataReportTypes: [],
    datahubChannelIds: [],
    dataReleaseTimes: [
      // dayjs().day(weekStart).format(dateFormat),
      // dayjs()
      //   .day(weekStart + 6)
      //   .format(dateFormat),
    ],
  });

  const [saveVerifyData, setSaveVerifyDataState] = useState<AssessWeekEmphasizeRecordData.SaveVerify>({
    isSaveVerify: 0,
  });

  /**
   * 获取 保存 验证
   * @param key
   */
  const loadSaveVerify = async () => {
    try {
      const response = await saveVerify();
      if (response.code === 0) {
        setSaveVerifyDataState(response.data);
      }
    } catch (error) {}
  };

  const columns: ProColumns<AssessWeekEmphasizeRecordData.RecordPage>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          区域
        </span>
      ),
      dataIndex: 'areaName',
      align: 'center',
      width: '120px',
      hidden: access.传播质效x配置x运营员,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          状态
        </span>
      ),
      dataIndex: 'areaName',
      align: 'center',
      width: '120px',
      render: (dom, entity, index, action) => {
        let color = '';
        let label = '';
        if (entity.isExamine == 1) {
          color = '-';
          label = '-';

          if (entity.state == 1) {
            color = '-';
            label = '-';

            if (entity.isExhibition == 1) {
              color = 'orange';
              label = '三好作品';
              return entity.exhibitionRangeNames.map((item: string) => (
                <Tag color={color}>{item}</Tag>
              ));
            }
          } else if (entity.state == 0) {
            color = '#faad14';
            label = '主动下架';
            return <Tag color={color}>{label}</Tag>;
          }
        } else if (entity.isExamine == 0) {
          color = 'red';
          label = '已被下架';
          return <Tag color={color}>{label}</Tag>;
        }
        return <></>;
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          报道类型
        </span>
      ),
      width: '100px',
      dataIndex: 'dataReportType',
      align: 'center',
      render: (dom, entity, index, action) => {
        let color = '';
        let label = '';

        if (entity.dataReportType == 1) {
          color = 'green';
          label = '好报道';
        } else if (entity.dataReportType == 2) {
          color = 'blue';
          label = '好评论';
        } else if (entity.dataReportType == 3) {
          color = 'orange';
          label = '好创意报道';
        }

        return <Tag color={color}>{label}</Tag>;
      },
    },

    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          标题
        </span>
      ),
      dataIndex: 'dataName',
      align: 'center',
      copyable: true,
      ellipsis: true,
      width: '20%',
      render: (dom, entity, index, action) => (
        <div
          style={{
            textAlign: 'left',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
          }}
        >
          <DetailRecord
            entrance="record"
            id={entity.id}
            trigger={
              <a
                target="_blank"
                style={{
                  textAlign: 'start',
                  textDecoration: entity.state == 0 ? 'line-through red' : '',
                }}
              >
                {entity.dataName}
              </a>
            }
            onRefurbish={function (): void {
              actionRef?.current?.reload();
            }}
            onExhibitionRefurbish={function (): void {
              actionRef?.current?.reload();
            }}
          />
        </div>
      ),
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          平台
        </span>
      ),
      dataIndex: 'datahubChannelName',
      align: 'center',
      width: '120px',
      render: (dom, entity, index, action) => {
        return (
          <Flex justify={'center'} align={'center'}>
            {entity?.datahubChannelNames?.map((item) => {
              let icon;
              if (item == '微信公众号') {
                icon = <IconWeChatOfficialAccount width={15} height={15} />;
              } else if (item == '微信视频号') {
                icon = <IconWeChatChannels width={15} height={15} />;
              } else if (item == '微博') {
                icon = <IconWeibo width={15} height={15} />;
              } else if (item == '抖音') {
                icon = <IconDouyin width={15} height={15} />;
              } else if (item == '今日头条') {
                icon = <IconToutiao width={15} height={15} />;
              } else if (item == '快手') {
                icon = <IconKuaishou width={15} height={15} />;
              } else if (item == '哔哩哔哩') {
                icon = <IconBiliBili width={15} height={15} />;
              } else if (item == '客户端') {
                icon = <IconApp width={15} height={15} />;
              } else if (item == '网站') {
                icon = <IconWeb width={15} height={15} />;
              }
              return icon;
            })}
          </Flex>
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          阅读量/播放量
        </span>
      ),
      dataIndex: 'dataReadCount',
      align: 'center',
      // sorter: true,
      width: '85px',
      render: (dom, entity, index, action) => {
        let dataReadCount = entity.dataReadCount | 0;
        let dataPlayCount = entity.dataPlayCount | 0;
        return <span>{dataReadCount + dataPlayCount}</span>;
      },
    },
    // {
    //   title: (
    //     <span
    //       style={{
    //         color: '#99a3b7',
    //         fontSize: 12,
    //         textAlign: 'center',
    //         fontWeight: 'normal',
    //       }}
    //     >
    //       阅读量
    //     </span>
    //   ),
    //   dataIndex: 'dataReadCount',
    //   align: 'center',
    //   // sorter: true,
    //   width: '85px',
    //   render: (dom, entity, index, action) => {
    //     if (
    //       entity.datahubChannelNames.includes('微信公众号') ||
    //       entity.datahubChannelNames.includes('微博') ||
    //       entity.datahubChannelNames.includes('今日头条')
    //     ) {
    //       return <span>{entity.dataReadCount}</span>;
    //     } else {
    //       return <>-</>;
    //     }
    //   },
    // },
    // {
    //   title: (
    //     <span
    //       style={{
    //         color: '#99a3b7',
    //         fontSize: 12,
    //         textAlign: 'center',
    //         fontWeight: 'normal',
    //       }}
    //     >
    //       播放量
    //     </span>
    //   ),
    //   dataIndex: 'dataPlayCount',
    //   align: 'center',
    //   // sorter: true,
    //   width: '85px',
    //   render: (dom, entity, index, action) => {
    //     if (
    //       entity.datahubChannelNames.includes('抖音') ||
    //       entity.datahubChannelNames.includes('微信视频号')
    //     ) {
    //       return <span>{entity.dataPlayCount}</span>;
    //     } else {
    //       return <>-</>;
    //     }
    //   },
    // },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          点赞量
        </span>
      ),
      dataIndex: 'dataLikeCount',
      align: 'center',
      // sorter: true,
      width: '85px',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          转发量
        </span>
      ),
      dataIndex: 'dataCollectCount',
      align: 'center',
      // sorter: true,
      width: '85px',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          发布日期
        </span>
      ),
      dataIndex: 'dataReleaseTime',
      align: 'center',
      width: '100px',
      render: (dom, entity, index, action) => {
        return dayjs(entity.dataReleaseTime).format('YYYY-MM-DD');
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: '120px',
      fixed: 'right',
      render: (_, row, index, action) => [
        <a
          key="a_reset_bind_wechat"
          onClick={async () => {
            const response = await forwardRecordToMonth({ id: row.id });
            if (response.code === 0) {
              message.success('重置成功');
            }
          }}
        >
          转发到月度
        </a>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '传播质效-重要稿件',
        // subTitle: (

        // ),
        breadcrumb: {
          items: [],
        },
        extra: [
          <ModalForm
            key={'modal_form_release_state_discard'}
            autoFocusFirstInput
            trigger={
              <Alert
                message={
                  <>
                    展示地址：
                    <a>三好作品</a>
                  </>
                }
                type="info"
                showIcon
              />
            }
            title={
              <Alert
                message={
                  <>
                    展示地址：
                    <a target={'_blank'} href="https://assess.ljsyy.net">
                      三好作品
                    </a>
                  </>
                }
                type="info"
                showIcon
                style={{
                  width: '300px',
                }}
              />
            }
            modalProps={{
              width: '650px',
              destroyOnClose: true,
            }}
            submitter={false}
          >
            <iframe src="https://assess.ljsyy.net" height="900" width="100%" frameBorder="0" />
          </ModalForm>,
          <TableExhibition />,
          <Alert
            message={'无特殊情况，每周一17点关闭填报入口'}
            type="info"
            showIcon
            style={{
              width: '300px',
            }}
          />,
          saveVerifyData?.isSaveVerify == 1 && (
            <AddRecord
              onRefurbish={function (): void {
                actionRef.current?.reload();
              }}
            />
          ),
        ],
      }}
    >
      <Alert
        message="三好作品统计范围为微博、微信公众号、抖音、微信视频号、今日头条号、快手、哔哩哔哩、客户端、网站。可填报同一稿件，多个平台链接或佐证材料。阅读量、播放量、转发数、点赞数累加计算。"
        type="success"
        showIcon
      />
      <ProTable<AssessWeekEmphasizeRecordData.RecordPage>
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        request={async (params = {}, sorter) => {
          loadSaveVerify();
          const response = await pageRecord({
            ...params,
            ...searchParam,
          });
          return {
            data: response.data?.data,
            success: true,
            total: response.data?.total,
          };
        }}
        dateFormatter="id"
        defaultSize={'small'}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        search={false}
        options={{
          density: false,
          setting: false,
        }}
        ghost
        scroll={{
          x: '1100px',
        }}
        headerTitle={''}
        toolbar={{
          search: {
            allowClear: true,
            onSearch: (value: string) => {
              setSearchParamState({
                ...searchParam,
                dataName: value,
              });
              actionRef.current?.reloadAndRest();
            },
          },
          filter: (
            <Space>
              <Select
                placeholder="全部状态"
                variant="filled"
                defaultValue={''}
                style={{ width: '110px' }}
                options={[
                  { value: '', label: '全部状态' },
                  { value: '2', label: '三好作品' },
                  { value: '1', label: '正常' },
                  { value: '0', label: '主动下架' },
                ]}
                onChange={(value) => {
                  if (value == '') {
                    setSearchParamState({
                      ...searchParam,
                      states: [],
                    });
                  } else {
                    setSearchParamState({
                      ...searchParam,
                      states: [value],
                    });
                  }

                  actionRef.current?.reloadAndRest();
                }}
              />

              <Select
                placeholder="全部类型"
                variant="filled"
                defaultValue={'0'}
                style={{ width: '110px' }}
                options={[
                  { value: '0', label: '全部类型' },
                  { value: '1', label: '好报道' },
                  { value: '2', label: '好评论' },
                  { value: '3', label: '好创意报道' },
                ]}
                onChange={(value) => {
                  if (value == '0') {
                    setSearchParamState({
                      ...searchParam,
                      dataReportTypes: [],
                    });
                  } else {
                    setSearchParamState({
                      ...searchParam,
                      dataReportTypes: [value],
                    });
                  }

                  actionRef.current?.reloadAndRest();
                }}
              />
              <Select
                placeholder="全部平台"
                variant="filled"
                defaultValue={'0'}
                style={{ width: '110px' }}
                options={[
                  { value: '0', label: '全部平台' },
                  { value: '8117112412962885', label: '微信公众号' },
                  { value: '8117112412962886', label: '微信视频号' },
                  { value: '8117112414076995', label: '微博' },
                  { value: '8117112414994505', label: '抖音' },
                  { value: '8117112419123365', label: '今日头条' },
                  { value: '8117112411979845', label: '客户端' },
                  { value: '8117112410996805', label: '网站' },
                ]}
                onChange={(value) => {
                  if (value == '0') {
                    setSearchParamState({
                      ...searchParam,
                      datahubChannelIds: [],
                    });
                  } else {
                    setSearchParamState({
                      ...searchParam,
                      datahubChannelIds: [value],
                    });
                  }

                  actionRef.current?.reloadAndRest();
                }}
              />

              <DatePicker.RangePicker
                // defaultValue={[dayjs().day(weekStart), dayjs().day(weekStart + 6)]}
                maxDate={dayjs()}
                format={dateFormat}
                variant="filled"
                allowClear={false}
                style={{ width: '240px' }}
                onChange={(dates, dateStrings) => {
                  setSearchParamState({
                    ...searchParam,
                    dataReleaseTimes: dateStrings.map((item) => item + ' 00:00:00'),
                  });
                  actionRef.current?.reloadAndRest();
                }}
              />
            </Space>
          ),
        }}
        // tableExtraRender={(_, data) => (
        //   <Card>
        //     <Descriptions size="small" column={3}>
        //       <Descriptions.Item label="总量">{data.length}</Descriptions.Item>
        //       <Descriptions.Item label="本周">Lili Qu</Descriptions.Item>
        //       <Descriptions.Item label="三周内">
        //         <a>421421</a>
        //       </Descriptions.Item>
        //       <Descriptions.Item label="统计数据">2017-01-10</Descriptions.Item>
        //       <Descriptions.Item label="汇总数据">2017-10-10</Descriptions.Item>
        //     </Descriptions>
        //   </Card>
        // )}
      />
    </PageContainer>
  );
};
export default TabRecord;
